package com.LeeCode;

/**
 * 统计完全子字符串
 */

public class Code2953 {
    public static void main(String[] args) {
        String word = "igigee";
        int k = 2;
        System.out.println(new Code2953().countCompleteSubstrings(word, k));
    }

    public int countCompleteSubstrings(String word, int k) {
        int n = word.length();
        int ans = 0, index = 0;

        while (index < n) {
            int start = index;
            // 寻找区间
            for (index++; index < n && Math.abs(word.charAt(index) - word.charAt(index - 1)) <= 2; index++) ;
            ans += aux(word.substring(start, index), k);
        }

        return ans;
    }

    private int aux(String S, int k) {
        int ans = 0;
        char[] chars = S.toCharArray();

        for (int m = 1; m <= 26 && m * k <= S.length(); m++) {
            int[] cnt = new int[26];
            for (int right = 0; right < chars.length; right++) {

                // 入
                cnt[chars[right] - 'a']++;

                int left = right + 1 - m * k;

                // 更新
                if (left >= 0) {
                    boolean flag = true;
                    for (int i = 0; i < 26; i++) {
                        if (cnt[i] > 0 && cnt[i] != k) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        ans++;
                    }
                    // 出
                    cnt[chars[left] - 'a']--;
                }
            }
        }

        return ans;
    }
}
